import socket
import threading


def tcp_service():
    port = 9081
    host = '192.168.1.103'

    tcp_service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_service.bind((host, port))
    tcp_service.listen(200)
    print(f"服务器已启动，主机地址为：{host}:{port},等待tcp连接")
    try:
        while True:
            # 接受TCP连接
            client_socket, addr = tcp_service.accept()
            print(f"已连接到{addr}")
            # 接受数据，定义字节数
            data = client_socket.recv(1024)
            # 打印收到的数据
            print(f"接受数据是{data.decode()}")
            tcp_service.sendall(b"ACK: Handshake success")
            # 关闭连接
            client_socket.close()
    except KeyboardInterrupt as e:
        print(f"服务端手动停止，错误信息为{e}")
    except ConnectionError as e:
        print(f"客户端断开连接，错误信息为：{e}")
    except KeyError as e:
        print(f"远程客户端发送数据错误，{e}")
    except OSError as e:
        print(f"触发系统连接错误，错误信息为：{e}")
    # finally:
    #     tcp_service.close()


def ts(bind_addr: tuple) -> None:
    TTL = 2
    buffer = 1024
    # 创建实例
    socket_sevice = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket_sevice.bind(bind_addr)  # bind接收元组对象，绑定IP地址
    # listen方法监听bind方法地址连接上来的tcp客户端
    socket_sevice.listen(5)  # 此处参数为整数，允许5个tcp客户端连接
    print(f"主机地址：{bind_addr}等待用户连接")
    while True:

        # accept方法阻塞通道，等待连接
        data_socket, addr = socket_sevice.accept()
        data_socket.recv(buffer)  # 接收数据包最大数1024
        if not data_socket:
            # 如果接收数据为空，说明客户端关闭了连接
            print(f"客户端{addr}断开连接")
            data_socket.close()
            continue
        received = data_socket.recv(buffer)
        print_info = received.decode('utf-8')
        print(f"tcp客户端{addr}已连接，接收到数据{print_info}")
    # if not dataSocket:
    #     print(f"TCP客户端：{addr}已经连接成功，发送{dataSocket}数据")
    # socket_sevice.sendto('hello world'.encode(),addr)
    # print(f"已发送")


if __name__ == '__main__':
    ts(('192.168.1.107', 5003))
